import {Component, OnInit} from '@angular/core';
import {PageEntity} from '../../../core/domain/page.entity';
import {Device} from './device';
import {DeviceManageService} from './device-manage.service';
import {Response} from '../../../core/domain/response';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';
import {HTTP_BASE_URL, SERVERS_NAME} from '../../../config/config';
import {StorageUtil} from '../../../utils/storage.util';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CopyUtil} from '../../../utils/copy.util';
import {DatePipe} from '@angular/common';
import {StatusEnum} from '../../../core/enum/status.enum';
import {FilterEnum} from '../../../core/enum/filter.enum';
import {SourceServer} from '../../../common/source.server';
import {OtherUtil} from '../../../utils/other.util';

declare var $: any;

@Component({
    selector: 'app-device-manage',
    templateUrl: './device-manage.component.html',
    styleUrls: ['./device-manage.component.scss'],
    providers: [DeviceManageService, SourceServer]
})
export class DeviceManageComponent implements OnInit {
    roomInfo = [];
    isEdit = false;
    isRoom = false;
    // 是否打开编辑框
    isAddEdit = false;
    // 设备编号
    deviceNumber = null;
    // 设备名称
    deviceName = null;
    // 分页查询条件
    pageInfo: PageEntity = new PageEntity();

    // 设备列表
    list: Device[] = [];
    // 单条设备信息
    device: Device = new Device();

    // 记录页面列表选中信息
    displayList = [];
    // 全选状态
    isAllCheck = false;
    // 页面数据转变状态
    isIndeterminate = false;
    // 页面选中id
    mapOfCheckedId: { [key: string]: boolean } = {};
    // 设备标识列表
    deviceIdentifiesList: DeviceType[] = [];
    deviceTypeList: DeviceType[] = [];
    // 负责人列表
    userList: UserList[] = [];
    // 设备使用状态列表
    statusList = [
        {value: 0, text: '在用'},
        {value: 1, text: '停用'},
        {value: 2, text: '报废'}
    ];
    buyDate: Date = new Date();
    buildDate: Date = new Date();
    fileList: UploadFile[] = [];
    fileListImport: UploadFile[] = [];
    fileDocList: UploadFile[] = [];
    uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;
    uploadUrlDoc = `${SERVERS_NAME.UPLOAD_DOC}`;
    linkInfo = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`;
    headerInfo = null;

    validateForm: FormGroup;
    roomTree: any[] = [];
    canDelete = true;

    // excel导入
    showExcelModal = false;
    headerInfoExcel = null;

    // 导入的Excel 名称
    importExcelName = '';
    previewImage: string | undefined = '';
    previewVisible = false;
    showUploadList = {
        showPreviewIcon: true,
        showRemoveIcon: true,
        hidePreviewIconInNonImage: true
    };

    constructor(
        public pageServe: DeviceManageService,
        private message: NzMessageService,
        private formBuilder: FormBuilder,
        private datePip: DatePipe,
        private sourceServe: SourceServer
    ) {
    }

    ngOnInit() {
        this.device.identifies = [];
        const token = StorageUtil.getLocalStorage('token');
        this.headerInfo = StorageUtil.getFileHeader();
        // 查询设备标识
        this.searchDeviceFn();
        // 设备类型列表
        this.deviceList();
        // 负责人列表
        this.leaderList();

        // 树列表
        this.treeList();
        this.initForm();
        // 图片上传头部
        this.headerInfoExcel = StorageUtil.getFileHeader();
    }

    /**
     * 树列表
     */
    treeList(): void {
        this.pageServe.treeWithRoom().subscribe(res => {
            const {status, datas} = res;
            if (status === StatusEnum.SUCCESS) {
                this.roomTree = datas;
            }
        });
    }

    /**
     * 负责人列表
     */
    leaderList(): void {
        this.pageServe.userList().subscribe(res => {
            const {status, datas} = res;
            if (status === StatusEnum.SUCCESS) {
                this.userList = datas;
            }
        });
    }

    /**
     * 设备类型列表
     */
    deviceList(): void {
        this.pageServe.deviceTypeList().subscribe(res => {
            const {status, datas} = res;
            if (status === StatusEnum.SUCCESS) {
                this.deviceTypeList = datas;
            }
        });
    }

    /**
     * 查询设备标识
     */
    searchDeviceFn(): void {
        this.pageServe.deviceIdentifiesList().subscribe((res: Response) => {
            const {status, datas} = res;
            if (status === StatusEnum.SUCCESS) {
                this.deviceIdentifiesList = datas;
                this.deviceIdentifiesList.forEach(item => {
                    item['text'.toString()] = item.keyCode;
                    item['value'.toString()] = item.keyValue;
                });
                // 查询页面列表
                this.pageList();
            }
        });
    }

    initForm() {
        this.validateForm = this.formBuilder.group({
            // 设备新增，更新参数
            description: [null, []],
            //  采购日期
            buyDate: [null, []],
            buildDate: [null, []],

            // 设备类型
            deviceType: [null, [Validators.required]],
            // 设备标识
            identifies: [null, [Validators.required]],
            // 安装位置
            installPos: [null, []],
            // 设备简介
            introduce: [null, []],
            // ip地址
            ipAddr: [null, []],
            // 生产商
            manufacturer: [null, []],
            // 设备名称
            name: [null, [Validators.required]],
            // 设备编号
            number: [null, [Validators.required]],
            // 备注
            remark: [null, []],
            // 房间id
            roomId: [null, [Validators.required]],
            // 规格型号
            specModel: [null, [Validators.required]],
            // 设备图片
            sourceIds: [null, []],
            // 设备状态。0.在用；1.停用；2.报废
            status: [null, [Validators.required]],
            // 供应商
            supplier: [null, []],
            // 负责人id
            userId: [null, [Validators.required]],
            roomName: [null, [Validators.required]],
            // 国资标号
            gradeCode: [null, []]
        });
    }

    /**
     * 页面全选
     * @param event 全选状态
     */
    checkAll(event: boolean): void {
        this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = event));
        this.refreshStatus();
    }

    /**
     * 置换页面各数据选中状态
     */
    refreshStatus(): void {
        this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
        this.isIndeterminate =
            this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
            !this.isAllCheck;
        this.checkDelete();
    }

    handlePreview = (file: UploadFile) => {
        this.previewImage = file.url || file.thumbUrl;
        this.previewVisible = true;
    }

    /**
     * 页面数据转化时触发
     * @param event 是否转变
     */
    currentPageDataChange(event): void {
        this.displayList = event;
        this.refreshStatus();
    }

    /**
     * 判断是否选择了数据
     */
    checkDelete(): void {
        this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
    }

    /**
     * 页面转变
     * @param event 页码
     */
    searchPageIndex(event) {
        this.pageInfo.first = event;
        this.pageList();
    }

    /**
     * 每页查询条数转变
     * @param event 显示条数
     */
    searchPageSize(event) {
        this.pageInfo.rows = event;
        this.pageInfo.first = 1;
        this.pageList();
    }

    /**
     * 表格信息筛选
     * @param event 筛选状态
     * @param flag 筛选字段
     */
    filterSome(event, flag) {
        if (event.length > 0) {
            this.pageInfo.first = 1;
            this.pageInfo['filters'.toString()][flag] = {
                matchMode: FilterEnum.IN,
                value: event.join(',')
            };
        } else {
            this.pageInfo['filters'.toString()][flag] = undefined;
        }
        this.pageList();
    }

    /**
     * 查询设备列表
     */
    pageList() {
        this.pageServe.pageFarm(this.pageInfo, [
            {name: 'name', value: this.deviceName},
            {name: 'number', value: this.deviceNumber}
        ]);
        this.pageServe.page(this.pageInfo).subscribe((res: Response) => {
            const {datas, status} = res;
            if (status === StatusEnum.SUCCESS) {
                const {data, totalRecords} = datas;
                this.list = data;
                this.pageInfo.totalRecords = totalRecords;
            }
        });
    }

    /**
     * 新增按钮事件
     */
    addbtn() {
        this.isEdit = false;
        this.isAddEdit = true;
        this.initForm();
        this.device = new Device();
        this.fileList = [];
        this.fileDocList = [];
        this.showUploadList.showRemoveIcon = true;
    }


    /**
     * 编辑设备信息
     */
    editDevce(id, isEdit) {
        this.fileList = [];
        this.fileDocList = [];
        isEdit ? this.isEdit = true : this.isEdit = false;
        this.device = new Device();
        this.pageServe.view(id).subscribe((res: Response) => {
            const {status, datas} = res;
            if (status === StatusEnum.SUCCESS) {
                this.device = CopyUtil.deepCopy(datas, {});
                if (datas.buyDate) {
                  this.buyDate = new Date(datas.buyDate);
                } else {
                  this.buyDate = null;
                }
                if (datas.buildDate) {
                  this.buildDate = new Date(datas.buildDate);
                } else {
                  this.buildDate = null;
                }
                this.isAddEdit = true;
                // 需要重新编辑
                if (res.datas.sources != null) {
                    const te = [];
                    res.datas.sources.forEach(item => {
                        const test = {
                            uid: item.id,
                            name: item.fileOriginalName,
                            status: 'done',
                            url: item.url = this.linkInfo + 'source/view/' + item.moduleName + '/' + item.fileNewName
                        };
                        te.push(test);
                    });
                    this.fileList = [...te];
                }
            }
        });
        this.showUploadList.showRemoveIcon = true;
        if (isEdit) {
            this.showUploadList.showRemoveIcon = false;
        }
    }

    /**
     * 删除设备通过选中Id
     * @param deviceId 设备id 存在为单条删除 不存在为多条删除
     */
    delete(deviceId: string): void {
        let ids = [];
        if (deviceId) {
            ids = [deviceId];
        } else {
            for (const val in this.mapOfCheckedId) {
                if (this.mapOfCheckedId[val]) {
                    ids[ids.length] = val;
                }
            }
        }
        if (ids.length === 0) {
            this.message.warning('请选勾选需要删除的设备!');
            return;
        }
        this.pageServe.deviceDelete(ids).subscribe((res: Response) => {
            const {status, message} = res;
            if (status === StatusEnum.SUCCESS) {
                this.mapOfCheckedId = {};
                this.pageList();
                this.message.success(message);
            }
        });
    }

    cancelFn(): void {
        this.canDelete = true;
        this.isAllCheck = false;
        this.mapOfCheckedId = {};
        this.isIndeterminate = false;
    }

    /**
     * 删除上传资源
     * @param file s
     */
    deleteFlile = (file: UploadFile) => {
        if (this.isEdit) {
            $('.ant-upload-list-item').find('nz-icon').css('display', 'none');
            return false;
        } else {
            $('.ant-upload-list-item').find('nz-icon').css('display', '');
        }
        const temList = [];
        this.fileList.forEach((item) => {
            if (item.uid === file.uid) {
                this.sourceServe.deleteFile([item.uid]).subscribe(res => {
                    if (res.status === StatusEnum.SUCCESS) {
                        this.message.success('文件删除成功!');
                    }
                });
            } else {
                temList.push(item);
            }
        });
        this.fileList = temList;
    }

    /**
     * 附件上传回调
     * @param event 上传回调信息
     */
    getUploadInfo(event) {
        const {file, fileList, type} = event;
        if (type === 'success') {
            if (file.response.status === StatusEnum.SUCCESS) {
                fileList.forEach((item) => {
                    if (item.response) {
                        const datas = item.response.datas;
                        item.uid = datas.id;
                        item.url = this.linkInfo + 'source/view/' + datas.moduleName + '/' + datas.fileNewName;
                    }
                });
                this.fileList = fileList;
            } else {
                this.message.warning('文件上传失败,请移除文件!');
            }
        }
    }

    /**
     * 将doc文件转化为html
     * @param event s
     */
    getUploadDoc(event) {
        const {file, fileList, type} = event;
        if (type === 'success') {
            const {datas, status} = file.response;
            if (status === StatusEnum.SUCCESS) {
                fileList.splice(0, fileList.length);
                this.device.introduce = datas;
            }
        }
    }

    /**
     * 保存编辑信息
     */
    submit() {
        const data = CopyUtil.deepCopy(this.device, {});
        let postName = 'create';
        if (this.device.id) {
            postName = 'update';
        }
        data.sourceIds = [];
        this.fileList.forEach(item => {
            data.sourceIds.push(item.uid);
        });
        data.buyDate = this.datePip.transform(this.buyDate, 'yyyy-MM-dd');
        data.buildDate = this.datePip.transform(this.buildDate, 'yyyy-MM-dd');
        this.pageServe[postName](data).subscribe((res: Response) => {
            const {status, message} = res;
            if (status === StatusEnum.SUCCESS) {
                this.isAddEdit = false;
                this.pageList();
                this.message.success(message);
            }
        });
    }

    /**
     * 获取房间信息
     */
    getRoomInfo(event) {
        this.device.roomId = event[0];
        this.device.roomName = event[1];
        this.isRoom = false;
    }


    /**
     * 导入
     */
    importShow() {
        this.showExcelModal = true;
    }


    /**
     * @author leihfei
     * @date 2019-06-01
     * @description 删除导入的文件
     */
    delFile() {
        this.fileListImport = [];
        this.importExcelName = '';
    }


    /**
     * 导出
     */
    exportShow() {
        window.location.href = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}sys/equipment/down/downExcel`;
        this.message.success('导出成功!');
    }

    /**
     * 模板下载
     */
    exportExclShow() {
        window.location.href = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}sys/equipment/down/downMBExcel`;
    }

    /**
     * @author leihfei
     * @date 2019-06-01
     * @description 手动上传文件
     */
    handleUpload(): void {
        if (!this.fileListImport || this.fileListImport.length === 0) {
            this.message.warning('请选择上传文件!');
            return;
        }
        const formData = new FormData();

        this.fileListImport.forEach((file: any) => {
            formData.append('file', file);
        });

        // 执行导入
        this.pageServe.importExcel(formData).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.message.success('导入成功!');
                this.showExcelModal = false;
                // 清除导入文件id
                this.importExcelName = '';
                this.pageList();
            }
        });
    }

    /**
     * 文件上传前
     * @ param file
     */
    beforeUpload = (file: UploadFile): boolean => {
        this.fileListImport = [];
        this.fileListImport.push(file);
        this.importExcelName = file.name;
        return false;
    }

}

export class DeviceType {
    id?: string;
    text?: string;
    value?: string;
    keyValue?: string;
    keyCode?: string;
}

export class UserList {
    id?: string;
    name?: string;
}
